# Convenience functions



# parameters
latexnums.Rda <- file.path(outputs,"latexnums.Rda")
latexnums.tex <- file.path(outputs,"latexnums.tex")

if (file.exists(latexnums.Rda)) {
  print(paste0("File for export to LaTeX found: ",latexnums.Rda))
} else {
  latexnums <- tibble(field="versionreg",value=as.character(date()),updated=date())
  saveRDS(latexnums,latexnums.Rda)
}

update_latexnums <- function(field,value) {
  # should test if latexnums is in memory
  latexnums <- readRDS(latexnums.Rda)
  
  # find out if a field exists
  if ( any(latexnums$field == field) ) {
    #message(paste0("Updating existing field ",field))
    latexnums[which(latexnums$field == field), ]$value <- as.character(value)
    latexnums[which(latexnums$field == field), ]$updated <- date()
    #return(latexnums)
  } else {
    #message(paste0("Adding new row for field ",field))
    latexnums <- latexnums %>% add_row(field=field,value=as.character(value),updated=date())
    #return(latexnums)
  }
  saveRDS(latexnums,latexnums.Rda)
}

# DOI citation function
get_citation_from_doi <- function(doi, format = "text") {
  tryCatch({
    rcrossref::cr_cn(dois = doi, format = format)
  }, error = function(e) {
    warning(paste("Could not retrieve citation for DOI:", doi))
    return(NULL)
  })
}

# Generate BibTeX file using rcrossref
generate_bibliography <- function() {
  bib_file <- file.path(basedir, "Scripts", "references.bib")
  
  # Get BibTeX entry from DOI
  tryCatch({
    bib_entry <- get_citation_from_doi(dv.doi, format = "bibtex")
    
    if (!is.null(bib_entry)) {
      # Replace the existing BibTeX key with our custom key
      # This removes everything from the opening brace to the first comma and replaces with custom key
      bib_cleaned <- gsub("(@[^{]+\\{)[^,]+,", "\\1aearegistry2025,", bib_entry)
      writeLines(bib_cleaned, bib_file)
    } else {
      warning("No BibTeX entry found for DOI: ", dv.doi)
    }
    
    message("Bibliography file generated:", bib_file, "\n")
    return(bib_file)
    
  }, error = function(e) {
    warning("Error generating bibliography: ", e$message)
    return(NULL)
  })
}